import * as api from "./api.js"
import CryptoJS from "../common/crypto.js"

//测试
//const key = 'N2ZhNDAyOTItNjA1YS00OTM0LWI0YWMtZDYwZmYzOTE2NTY1';
//正式
const key = 'MzMxZjIyYzQtMjg0OS00MTFhLWI4MjktMWE3NDhlNTQ0MTcz';

function encryptByDES(message) {
	let hash = CryptoJS.HmacSHA256(message, CryptoJS.enc.Base64.parse(key));
	let hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
	return hashInBase64
}

function getSign(data) {
	let _str = JSON.stringify(data);
	return encryptByDES(_str)
}
// 请求头处理函数
const DealWithHeader = (data) => {
	let header = {
		'content-type': 'application/json;charset=utf-8'
	}
	let sign = getSign(data);
	header['x-sign'] = sign;
	return header;
}

// 默认初始化数据
const requestData = {
	url: "",
	method: "POST",
	header: {
		"content-type": "application/json"
	},
	data: {},
	loading: false,
	mask: true,
	title: "数据加载中",
	failToast: false,
};

export const request = (reqData) => {
	let req = {
		...requestData,
		...reqData
	};
	let header = DealWithHeader(req.data);
	return new Promise((resolve, reject) => {
		if (req.loading) uni.showLoading({
			title: req.title,
			mask: req.mask
		});
		uni.request({
				url: req.url,
				data: JSON.stringify(req.data),
				method: req.method,
				header: header
			}).then((data) => {
				console.log(33,data)
				let [err, res] = data;
				if (err) {
					console.log(err);
					if (req.failToast)
						uni.showToast({
							title: "网络不好，请求失败！",
							duration: 3000,
							icon: "none"
						});
					reject(err);
					return;
				}
				if (res.data.code == 200 || res.data.code == 500 || res.data.code == 0) {
					resolve(res.data);
				} else {
					if (req.failToast && res.data.message) {
						uni.showToast({
							title: res.data.message,
							duration: 3000,
							icon: "none"
						});
					}
					reject(err);
				}
			})
			.finally(() => {
				if (req.loading) uni.hideLoading();
			});
	})
}


